import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { Version, VersionDiff } from '@/types/version'
import * as versionAPI from '@/services/versionAPI'

interface VersionState {
  versions: Version[]
  currentVersion: Version | null
  loading: boolean
  error: string | null
  versionDiff: VersionDiff | null
  loadingDiff: boolean
}

const initialState: VersionState = {
  versions: [],
  currentVersion: null,
  loading: false,
  error: null,
  versionDiff: null,
  loadingDiff: false,
}

// 异步thunks
export const fetchVersions = createAsyncThunk(
  'version/fetchVersions',
  async (scriptId: string) => {
    const response = await versionAPI.getVersionHistory(scriptId)
    return response.data
  }
)

export const fetchVersionById = createAsyncThunk(
  'version/fetchVersionById',
  async (id: string) => {
    const response = await versionAPI.getVersion(id)
    return response.data
  }
)

export const compareVersions = createAsyncThunk(
  'version/compareVersions',
  async ({ fromId, toId }: { fromId: string; toId: string }) => {
    const response = await versionAPI.compareVersions(fromId, toId)
    return response.data
  }
)

export const revertToVersion = createAsyncThunk(
  'version/revertToVersion',
  async ({ scriptId, versionId }: { scriptId: string; versionId: string }) => {
    const response = await versionAPI.revertToVersion(scriptId, versionId)
    return response.data
  }
)

const versionSlice = createSlice({
  name: 'version',
  initialState,
  reducers: {
    setCurrentVersion: (state, action: PayloadAction<Version | null>) => {
      state.currentVersion = action.payload
    },
    clearVersionDiff: (state) => {
      state.versionDiff = null
    },
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // fetchVersions
      .addCase(fetchVersions.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchVersions.fulfilled, (state, action) => {
        state.loading = false
        state.versions = action.payload.versions || []
      })
      .addCase(fetchVersions.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '获取版本历史失败'
      })
      // fetchVersionById
      .addCase(fetchVersionById.fulfilled, (state, action) => {
        state.currentVersion = action.payload
      })
      // compareVersions
      .addCase(compareVersions.pending, (state) => {
        state.loadingDiff = true
        state.versionDiff = null
      })
      .addCase(compareVersions.fulfilled, (state, action) => {
        state.loadingDiff = false
        state.versionDiff = action.payload
      })
      .addCase(compareVersions.rejected, (state, action) => {
        state.loadingDiff = false
        state.error = action.error.message || '版本比较失败'
      })
      // revertToVersion
      .addCase(revertToVersion.fulfilled, (state, action) => {
        // 添加新版本到列表顶部
        state.versions.unshift(action.payload)
      })
  },
})

export const {
  setCurrentVersion,
  clearVersionDiff,
  clearError,
} = versionSlice.actions

export default versionSlice.reducer